# --*-- coding=utf-8 --*--
"""
http请求的基础类
"""
from auto_test.lib.data_util import bytes_to_dict
from auto_test.lib.log_util import logger
import requests


class Request(object):
    """
    通用请求方法的封装
    """

    def __init__(self, request_url, request_headers, request_data, request_cookies=None):
        # 请求URL
        self.req_url = request_url
        # 请求消息头
        self.req_header = request_headers
        # 请求消息头的cookies
        self.req_cookie = request_cookies
        # 请求主体
        self.req_data = request_data

    def post(self, show_log_flag=True, **kwargs):
        """
        HTTP.post方法的logger
        :param show_log_flag: 是否输出log开关
        :param kwargs:
        :return:
        """
        if show_log_flag:
            logger.info('请求URL: ' + self.req_url)
            logger.info('请求消息头: ')
            logger.info(self.req_header)
            if self.req_cookie is not None:
                logger.info('请求cookies: ')
                logger.info(self.req_cookie)
            if self.req_data is not None:
                logger.info('请求Body: ')
                logger.info(bytes_to_dict(self.req_data))

        resp = requests.post(self.req_url, headers=self.req_header, data=self.req_data, cookies=self.req_cookie,
                             **kwargs)
        if show_log_flag:
            logger.info('响应body: ')
            logger.info(resp.content.decode('utf-8'))
            logger.info('-----------请求结束-------------------------')
        return resp
